package com.feng.controller;

import com.alibaba.fastjson2.JSONObject;
import com.feng.entity.User;
import com.feng.entity.vo.MessageVo;
import com.feng.repository.ChatHistoryRepository;
import com.feng.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.apache.coyote.Request;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RequiredArgsConstructor
@RestController
@RequestMapping("/ai/history")
public class ChatHistoryController {

    private final ChatHistoryRepository chatHistoryRepository;

    private final ChatMemory chatMemory;

    private final StringRedisTemplate redisTemplate;

    private final JwtUtil jwtUtil;

    @GetMapping("/{type}")
    public List<String> getChatIds(@PathVariable String type, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        if(token != null && token.startsWith("Bearer ")){
            token = token.substring(7);
            String id = jwtUtil.verifyToken(token);
            if(id != null){
                User user = JSONObject.parseObject(redisTemplate.opsForValue().get("login:" + id), User.class);
                if(user != null){
                    return chatHistoryRepository.getChatHistory(type, user.getAccount().getId());
                }
            }
        }
        return List.of("未登录");
    }

    @GetMapping("/details/{chatId}")
    public List<MessageVo> getChatHistory(@PathVariable String chatId){
        List<Message> messages = chatMemory.get(chatId, Integer.MAX_VALUE);
        if(messages.isEmpty()){
            return List.of();
        }
        return messages.stream().map(MessageVo::new).toList();
    }
}
